$NG.AllReady(function (page, { useValuesChange, useClick, useUpdateRow, useBeforeClick, useUpdateRows, useDataIndexChange, useAction }) {
    console.log("Data ready event triggered");

    var mstform = $NG.getCmpApi("p_form_impl_cost_budget");
    var dgrid1 = $NG.getCmpApi("p_form_impl_labor_budget"); //实施人工
    var dgrid2 = $NG.getCmpApi("p_form_impl_daliy_budget"); //日常费用
    var dgrid3 = $NG.getCmpApi("p_form_impl_sec_dev_budget"); //二次开发费用

    useBeforeClick(async ({ args }) => {
        let lock = true;
        if (page.isList) {
            const phid = page.getSelectedRecord()[0].phid;
            await $NG.execServer("getIsImpSSInfo", { source: phid }, (res) => {
                console.log(res);
                if (res.count == 0) return;
                $NG.alert("已被设备清单引用，无法反审核！");
                lock = false;
            });
        }
        return lock;
    }, "applycheck");

    ////////////////////////////////////////////////////////////--mstform

    //添加按钮
    $NG.getCmpApi("toolbar_p_form_impl_daliy_budget").insert({
        id: "fyadd",
        text: "选择费用项目",
        iconCls: "icon-New",
    });
    // 设置默认值人民币和汇率
    if (page.oType == "add") {
        $NG.updateState((updater) => {
            updater.data.p_form_impl_cost_budget.setProps({
                phid_fcur: {
                    label: "人民币",
                    value: 1,
                },
                exchangerate: 1,
            });
        });
    }
    getIsSSPayOne();
    async function getIsSSPayOne() {
        if (page.oType != "add") return;
        const phid_pc = mstform.getItem("phid_pc").getValue();
        if (!phid_pc) return;
        $NG.execServer("getIsSSPayOne", { phid_pc }, async (res) => {
            console.log(res);
            const _data = JSON.parse(res.data)[0].extendObjects;
            if (_data.num == 0) {
                window._addLock = false;
            } else {
                (await $NG.confirm("合同下已存在实施费用单！")) && $NG.close();
                window._addLock = true;
            }
        });
    }

    useBeforeClick(async ({ args }) => {
        if (window._addLock) {
            (await $NG.confirm("合同下已存在实施费用单！")) && $NG.close();
            return false;
        } else {
            return true;
        }
    }, "check");

    if (mstform) {
        console.log("mstform is ready");
        cntMFilter();
        getPtInfoByPhid();
        getCntCount("p_form_impl_cost_budget", "u_cnt", () => {
            getCntMInfoByPhid();
        });
        useValuesChange(({ args }) => {
            cntMFilter();
            getPtInfoByPhid();
            getCntCount("p_form_impl_cost_budget", "u_cnt", () => {
                getCntMInfoByPhid();
            });
        }, "p_form_impl_cost_budget.phid_pc");
        useValuesChange(({ args }) => {
            getCntMInfoByPhid();
        }, "p_form_impl_cost_budget.u_cnt");
        if (page.oType == "add") {
            mstform.getItem("bill_name").setValue(mstform.getItem("phid_pc").getText() || "" + "实施费用预算单");
            useValuesChange(({ args }) => {
                mstform.getItem("bill_name").setValue(mstform.getItem("phid_pc").getText() || "" + "实施费用预算单");
            }, "p_form_impl_cost_budget.phid_pc");
        }
    } else {
        console.error("mstform is not available");
    }
    // useUpdateRow(({args})=>{
    //     console.log(`监听到了`);
    //     const _arr = args[0]
    //     console.log(_arr.u_budget_account);
    //     const _isBy = [8570000000000621,8570000000000622]
    //     if(_arr.u_budget_account==8570000000000621||){
    //         $NG.alert("未包含项目激励。")
    //     }
    // },"p_form_impl_daliy_budget")8570000000000340   8570000000000341

    useBeforeClick(async () => {
        let lock = false;
        const _isBy = ["8570000000000340", "8570000000000341", "8570000000000368", "8570000000000369"];
        console.log(`监听到了`);
        const _arr = dgrid2.getStore().data;
        _arr.forEach((item) => {
            console.log("监听值", item.u_expense_code);
            if (_isBy.indexOf(String(item.u_expense_code)) !== -1) {
                lock = true;
            }
            console.log(item.u_expense_code);
        });
        if (window._addLock) {
            (await $NG.confirm("合同下已存在实施费用单！")) && $NG.close();
            return false;
        }
        if (!lock) {
            return await $NG.confirm("未包含项目激励！确定保存吗？");
        }
    }, "save");

    if (page.oType == "add" || page.oType == "edit") {
        $NG.updateState((updater) => {
            updater.data.p_form_impl_cost_budget.setProps({
                u_fitime: "FY" + formatDate(new Date(), "yyyy-mm").replace("-", ".M"),
            });
        });
        //表头多字段设置属性
        $NG.updateUI((updater) => {
            updater.fieldSetForm.p_form_impl_cost_budget.u_fitime.setProps({
                hidden: true, //隐藏
            });
        });
    }

    //自动带出所有费用项目
    // if (page.oType == "add") {
    //   $NG.execServer("getCostPc", { u_sequence: "02" }, (res) => {
    //     if (res.count == 0) return;
    //     const _data = JSON.parse(res.data);
    //     console.log(`费用项目`, _data);
    //     dgrid2.addRows(
    //       _data.reduce((value, item) => {
    //         const el = item.extendObjects;
    //         value.push({
    //           u_expense_code: el.phid,
    //           u_expense_code_EXName: el.u_name,
    //           // u_expense_description: el.u_describe,
    //         });
    //         return value;
    //       }, [])
    //     );
    //   });
    // }

    ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
    useDataIndexChange(({ args, instance }) => {
        var items = args[0];
        if (items.u_position) {
            $NG.execServer("getSimpleDataByPhid", { phid: items.u_position }, function (res) {
                if (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    // 尝试将 c_descript 转换为数字
                    const personnelRate = Number(datas.c_descript);
                    if (isNaN(personnelRate)) {
                        // 如果转换失败，可以设置一个默认值或者处理错误
                        console.error("Invalid value for u_personnel_rate:", datas.c_descript);
                    }
                    items.u_personnel_rate = personnelRate;
                    caculatedgrid();
                }
                dgrid1.refreshView();
            });
        }
        instance.updateRow(items);
    }, "p_form_impl_labor_budget.u_position");
    useUpdateRows(({ args }) => {
        caculatedgrid();
        args[0].forEach((item) => {
            if (!item.u_year) {
                item.u_year = new Date().getFullYear();
                item.u_year_EXName = new Date().getFullYear();
            }
        });
    }, "p_form_impl_labor_budget");
    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
    useUpdateRows(({ args }) => {
        caculatedgrid();
        //默认年度
        args[0].forEach((item) => {
            if (!item.u_year) {
                item.u_year = new Date().getFullYear();
                item.u_year_EXName = new Date().getFullYear();
            }
        });
        dgrid2.refreshView();
    }, "p_form_impl_daliy_budget");

    useUpdateRows(({ args }) => {
        caculatedgrid();
    }, "p_form_impl_sec_dev_budget");

    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                console.log("getPtInfoByPhid", res);
                if (res.count == 0) return;
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log("getPtInfoByPhid", datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_impl_cost_budget.setProps({
                        u_pc_overview: datas.descript,
                        u_pc_no: datas.pc_no, //项目编号
                        u_agreed_sts_dt: datas.start_date, //计划完工日期
                        u_agreed_pcl_dt: datas.end_date, //计划竣工日期
                        u_sqgw: {
                            //售前顾问
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        //大区
                        u_region: {
                            value: datas.phid_org_phid,
                            label: datas.phid_org_name,
                        },
                        u_regional_center: {
                            //区域中心
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        u_ywx: {
                            //产品线
                            value: datas.midwife_phid,
                            label: datas.midwife_name,
                        },
                        u_ywlx: {
                            //项目类型
                            value: datas.user_ywlx,
                            label: datas.ywlx_name,
                        },
                        phid_org: {
                            //部门
                            value: datas.org_phid,
                            label: datas.org_name,
                        },
                        u_pc_type: {
                            //项目类型
                            value: datas.type_phid,
                            label: datas.type_name,
                        },
                        u_pc_overview: datas.descript,
                    });
                });
                // 判断是否是提前施工
                let lock = true;
                if (datas.user_sf_tqsg == '1') {
                    lock = false
                } else {
                    lock = true
                }
                console.log(`是否提前施工项目`, datas.user_sf_tqsg);
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_impl_cost_budget.u_cnt.setProps({
                        required: lock
                    })
                })
                getIsSSPayOne();
            });
        }
    }

    function cntMFilter() {
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_impl_cost_budget.u_cnt.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = mstform.getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!mstform.getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 1,
                        phid_pc: mstform.getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }

    function getCntMInfoByPhid(params) {
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(`合同信息`, datas);
            $NG.updateState((updater) => {
                updater.data.p_form_impl_cost_budget.setProps({
                    u_cnt_no: datas.pcm_no, //合同编码
                    u_cnt_amt: datas.cnt_sum_fc, //合同
                    u_cnt_amt_vat: datas.cnt_sum_vat_fc, //合同
                    u_cnt_amt_qd: datas.cnt_sum_vat_fc, //合同签单金额
                    //发票类型
                    u_invoice_type: {
                        value: datas.invoice_type_phid,
                        label: datas.invoice_type_name,
                    },
                });
            });


        });
    }
    // 返回当月最大天数
    function getDaysInMonth(year, month) {
        const y = parseInt(year, 10);
        const m = parseInt(month, 10);
        return new Date(y, m, 0).getDate();
    }

    function caculatedgrid() {
        let u_total_impl_labor_amt = 0; //实施人工费
        let u_total_daily_amt = 0; //合计日常费用
        let u_total_sec_dev_amt = 0; //合计二次开发费用
        let u_total_impl_amt = 0; //合计总费用
        const Rows1 = dgrid1.getStore().data; //实施人工页签
        const Rows2 = dgrid2.getStore().data; //实施日常费用页签
        const Rows3 = dgrid3.getStore().data; //外包人工费用页签

        Rows1.forEach((items, rowIndex) => {
            let total = 0;
            for (let i = 1; i <= 12; i++) {
                const str = "u_man_days_" + String(i).padStart(2, "0");
                const manDays = Number(items[str]);
                let maxDay = getDaysInMonth(items.u_year, i);
                if (isNaN(manDays)) {
                    items[str] = 0;
                } else if (manDays > maxDay) {
                    items[str] = maxDay;
                    $NG.alert(`第${rowIndex + 1}行第${i}月人天不能超过${maxDay}天`);
                }
                total += Number(items[str] > 21.75 ? 21.75 : items[str]) || 0;
            }
            // 人月=人天/21.75
            // 人工费合计=人员费率*数量*人月
            items.u_man_months = total / 21.75;
            items.u_labor_amt = ((Number(items.u_personnel_rate) || 0) * (Number(items.u_qty) || 0) * (Number(items.u_man_months) || 0)).toFixed(2);
            u_total_impl_labor_amt += parseFloat(items.u_labor_amt || 0);
            dgrid1.refreshView();
        });
        Rows2.forEach((items) => {
            let total = 0;
            for (let i = 1; i <= 12; i++) {
                const str = "u_expenses_" + String(i).padStart(2, "0");
                total += Number(items[str]) || 0;
            }
            items.u_annual_impl_amt = total;
            u_total_daily_amt += parseFloat(items.u_annual_impl_amt || 0);
            dgrid2.refreshView();
        });
        Rows3.forEach((items) => {
            u_total_sec_dev_amt += parseFloat(items.u_sec_dev_amt || 0);
            dgrid3.refreshView();
        });

        u_total_impl_amt = u_total_impl_labor_amt + u_total_daily_amt + u_total_sec_dev_amt;

        $NG.updateState((updater) => {
            updater.data.p_form_impl_cost_budget.setProps({
                u_total_impl_labor_amt: u_total_impl_labor_amt, //
                u_total_daily_amt: u_total_daily_amt, //
                u_total_sec_dev_amt: u_total_sec_dev_amt, //
                u_total_impl_amt: u_total_impl_amt, //
                u_ss_rate: Number(mstform.getItem("u_cnt_amt").getValue()) != 0 ? Number(u_total_impl_amt) / Number(mstform.getItem("u_cnt_amt").getValue()) : 0,
            });
        });
    }
    payProjectFilter();
    function payProjectFilter() {
        $NG.updateUI((updater) =>
            updater.editGrid.p_form_impl_daliy_budget.u_expense_code.setProps((p) => {
                return {
                    ...p,
                    editor: {
                        ...p.editor,
                        clientSqlFilter: `u_sequence = '02' and phid != '8570000000000328'`
                    },
                };
            })
        );
    }
    // 格式化日期
    function formatDate(dateStr, outputFormat) {
        const date = new Date(dateStr);

        if (isNaN(date)) {
            return "无效的日期字符串";
        }

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");

        let formattedDate;

        switch (outputFormat) {
            case "yyyy-mm-dd":
                formattedDate = `${year}-${month}-${day}`;
                break;
            case "yyyy-mm-dd HH:mm":
                formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
                break;
            case "yyyy-mm":
                formattedDate = `${year}-${month}`;
                break;
            // 可以根据需要继续添加其他格式的处理逻辑
            default:
                formattedDate = "不支持的输出格式";
        }

        return formattedDate;
    }

    //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮////////////////////////////////////////////////////////
    //////////////////////////////////////插入按钮////////////////////////////////////////////////////////

    if (page.oType == "add" || page.oType == "edit") {
        useClick(async function ({ args }) {
            Fyxm();
        }, "fyadd");
    }
});

//获取合同数量
function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
        switch (res.count) {
            case 0:
                return;
            case 1:
                const datas = JSON.parse(res.data)[0].extendObjects;
                const temp_map = {};
                temp_map[key] = datas.phid;
                temp_map[`${key}_EXName`] = datas.bill_name;
                $NG.updateState((updater) => {
                    updater.data[table].setProps({
                        ...temp_map,
                    });
                    setTimeout(() => {
                        if (fun) {
                            fun();
                        }
                    }, 200);
                });
        }
    });
}

function Fyxm() {
    var dgrid2 = $NG.getCmpApi("p_form_impl_daliy_budget"); //日常费用

    // $NG.external.openNGHelp({
    //   type: "NGMultipleHelp",
    //   helpId: "cost_pc",
    //   valueField: "d.phid",
    //   labelField: "d.u_name",
    //   pageSize: 1000,
    //   //clientSqlFilter:  // 应用过滤条件
    // }).then((data) => {
    //   console.log(data);
    //   var gridArr = []; // 初始化 gridArr 数组
    //   console.log(data);
    //   for (var i = 0; i < data.length; i++) {
    //     // 列出需要赋值的表体字段
    //     var gridObj = {
    //       //u_expense_code: '',
    //     };
    //     // 对表体字段进行赋值, 可以取数据库中的值进行赋值
    //     gridObj.u_expense_code = data[i].origin.phid;
    //     gridObj.u_expense_code_EXName = data[i].origin.u_name;
    //     // 关键步骤：将 gridObj 添加到 gridArr 数组中
    //     gridArr.push(gridObj);
    //   }
    //   console.log(gridArr); // 确保这里打印出来的 gridArr 不是空的
    //   dgrid2.addRows(gridArr); // 将数据添加到表格组件中
    //   dgrid2.refreshView();
    // });

    $NG.external
        .openNGHelp({
            type: "NGMultipleHelp",
            helpId: "cost_pc_ss",
            valueField: "phid",
            labelField: "u_name",
            clientSqlFilter: `u_sequence = '02' and phid != '8570000000000328'`
        })
        .then((data) => {
            try {
                if (Array.isArray(data) && data.length > 0) {
                    var gridArr = [];
                    for (var i = 0; i < data.length; i++) {
                        var gridObj = {};
                        // gridObj.rel_key1 = data[i].origin.phid;
                        gridObj.u_expense_code = data[i].origin.phid || "";
                        gridObj.u_expense_code_EXName = data[i].origin.u_name || "";
                        gridArr.push(gridObj);
                    }
                    console.log(gridArr);
                    dgrid2.addRows(gridArr); // 将数据添加到表格组件中
                    dgrid2.refreshView();
                } else {
                    console.error("返回的数据无效或为空:", data);
                }
            } catch (error) {
                console.error("处理数据时出错:", error);
            }
        })
        .catch((error) => {
            console.error("打开NGHelp时发生错误:", error);
        });
}
